// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
import About from '@/views/About.vue';
import AuthPage from '@/views/AuthPage.vue';
import TestVuex from '@/views/TestVuex.vue';
import TestAxios from '@/views/TestAxios.vue';
import Layout2 from '@/views/Layout2.vue';
import ResetPassword from '@/views/ResetPassword.vue';
import SmtpSetting from '@/views/SmtpSetting.vue';
import SmtpInfo from '@/views/SmtpInfo.vue';
import NotFound from '@/views/NotFound.vue';
const isAuthenticated = () => !!localStorage.getItem('accessToken')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true },
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    meta: { requiresAuth: true },
  },
  {
    path: '/auth-page',
    name: 'auth-page',
    component: AuthPage,
    beforeEnter: (to, from, next) => {
      if (isAuthenticated()) {
        next('/layout') // 如果已登录，跳转到主页
      } else {
        next() // 未登录，继续进入登录页
      }
    },
  },
  {
    path: '/test-vuex',
    name: 'text-vuex',
    component: TestVuex
  },
    {
    path: '/test-axios',
    name: 'text-axios',
    component: TestAxios
  },
{
    path: '/layout',
    name: 'layout',
    component: Layout2,
    meta: { requiresAuth: true },
  },
  {
    path: '/reset-password',
    name: 'reset-password',
    component: ResetPassword,
  },
   {
    path: '/smtp',
    name: 'smtp',
    component: SmtpSetting,
  },
  {
    path:"/smtpinfo",
    name:"smtpinfo",
    component:SmtpInfo,
    meta: { requiresAuth: true },

  },
   // 404 错误页面路由
  {
    path: '/:pathMatch(.*)*',  // 匹配所有未定义的路由
    name: 'NotFound',
    component: NotFound,
  }

];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 路由守卫，检查是否需要登录
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('access_token'); // 获取 token
  if (to.meta.requiresAuth && !isAuthenticated()) {
    // 如果需要登录但没有 token，跳转到登录页
    next('/auth-page');
  } else {
    next();
  }
});

export default router;
